<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退款编号" prop="refundNo">
        <el-input
          v-model="queryParams.refundNo"
          placeholder="请输入退款编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售后状态" prop="oId">
        <el-input
          v-model="queryParams.oId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orders:shouhou:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orders:shouhou:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:shouhou:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:shouhou:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shouhouList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="退款编号" align="center" prop="refundNo" />
      <el-table-column label="关联订单" align="center" prop="oId" />
      <el-table-column label="售后状态" align="center" prop="afterSalesStatus" />
      <el-table-column label="退款金额" align="center" prop="order.actualPayment" />
      <el-table-column label="货物状态" align="center" prop="goodsStatus" />
      <el-table-column label="退款原因" align="center" prop="refundReason" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['orders:shouhou:list']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改售后管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shouhouRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退款编号" prop="refundNo">
          <el-input v-model="form.refundNo" placeholder="请输入退款编号" disabled/>
        </el-form-item>
        <el-form-item label="关联订单" prop="oId">
          <el-select v-model="form.oId" placeholder="请选择相应订单" @change="handleOrderChange">
            <el-option v-for="order in orderList" :key="order.orderId" :label="order.orderId" :value="order.orderId"></el-option>
          </el-select>
<!--          <el-input v-model="form.oId" placeholder="请输入订单编号" />-->
        </el-form-item>
        <el-form-item label="售后状态" prop="afterSalesStatus">
          <!-- 修改为下拉框 -->
          <el-select v-model="form.afterSalesStatus" placeholder="请选择售后状态">
            <el-option label="待处理" value="待处理" />
            <el-option label="售后中" value="售后中" />
            <el-option label="退款成功" value="退款成功" />
            <el-option label="退款失败" value="退款失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入退款金额" disabled/>
        </el-form-item>
        <el-form-item label="货物状态" prop="goodsStatus">
          <el-select v-model="form.goodsStatus" placeholder="请输入货物状态">
            <el-option label="未收到货" value="未收到货" />
            <el-option label="已收到货" value="已收到货" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker clearable
            v-model="form.applicationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shouhou">
import {
  checkOrderIdExists,
  listOrder,
  listShouhou,
  getShouhou,
  delShouhou,
  addShouhou,
  updateShouhou
} from "@/api/orders/shouhou"
import {listProduct} from "@/api/orders/order.js";
import{useRouter} from "vue-router";
const router = useRouter()
const { proxy } = getCurrentInstance()

const shouhouList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const orderList = ref([])


function lala() {
  loading.value = true
  listOrder().then(response => {
        console.log('接口返回数据:', response);
    orderList.value = response.rows
    response.rows.forEach(order => {
      orderMap.value.set(order.orderId, order)
    })
    loading.value = false
  })
}
onMounted(() => {
  lala()
})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    refundNo: null,
    afterSalesStatus: null,
    refundAmount: null,
    goodsStatus: null,
    refundReason: null,
    applicationTime: null
  },
  // 缓存订单信息
  orderMap: new Map(),
  rules: {
    refundNo: [
      { required: true, message: "退款编号不能为空", trigger: "blur" }
    ],
    afterSalesStatus: [
      { required: true, message: "售后状态不能为空", trigger: "blur" }
    ],
    refundAmount: [
      { required: true, message: "退款金额不能为空", trigger: "blur" }
    ],
    goodsStatus: [
      { required: true, message: "货物状态不能为空", trigger: "blur" }
    ],
    refundReason: [
      { required: true, message: "退款原因不能为空", trigger: "blur" }
    ],
    applicationTime: [
      { required: true, message: "申请时间不能为空", trigger: "blur" }
    ]
  }
})


// 当关联订单选择改变时触发
function handleOrderChange(orderId) {
  // Add null check
  if (form.value && orderMap.value.has(orderId)) {
    const order = orderMap.value.get(orderId)
    form.value.refundAmount = order.actualPayment
  }
}

function handleUpdate(row) {
  console.log(row);
  // 复制 row 对象，避免修改原始数据
  const rowToPass = { ...row };
  // 检查是否存在 order 对象，若存在则转换为 JSON 字符串
  if (rowToPass.order) {
    rowToPass.order = JSON.stringify(rowToPass.order);
  }
  router.push({
    path: '/detail',
    query: rowToPass
  });
}
const { queryParams, form, rules,orderMap  } = toRefs(data)

/** 查询售后管理列表 */
function getList() {
  loading.value = true
  listShouhou(queryParams.value).then(response => {
    shouhouList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    refundNo: null,
    afterSalesStatus: null,
    refundAmount: null,
    goodsStatus: null,
    refundReason: null,
    applicationTime: null
  }
  proxy.resetForm("shouhouRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
// 初始化计数器，存储在本地存储中，保证页面刷新后数值不丢失
const counter = ref(parseInt(localStorage.getItem('refundCounter')) || 0)

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 生成退款编号
  const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  const randomDigits = Math.floor(100 + Math.random() * 900);
  const counterStr = String(counter.value).padStart(4, '0');
  form.value.refundNo = `Th${currentDate}${randomDigits}${counterStr}`;
  // 计数器递增
  counter.value++;
  // 将计数器的值存储到本地存储
  localStorage.setItem('refundCounter', counter.value.toString());
  open.value = true
  title.value = "添加售后管理"
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   reset()
//   reset()
//   const _id = row.id || ids.value
//   getShouhou(_id).then(response => {
//     form.value = response.data
//     open.value = true
//     title.value = "修改售后管理"
//   })
// }

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shouhouRef"].validate(async valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShouhou(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        try {
          console.log('开始检查订单号是否重复，订单号:', form.value.oId);
          // 检查订单号是否重复
          const isOrderIdExists = await checkOrderIdExists(form.value.oId)
          console.log('订单号重复检查接口响应:', isOrderIdExists);
          if (typeof isOrderIdExists !== 'boolean') {
            console.error('接口返回数据异常:', isOrderIdExists);
            proxy.$modal.msgError("检查订单号失败，请稍后重试！")
            return;
          }
          if (isOrderIdExists) {
            proxy.$modal.msgWarning("该订单号已存在，请勿重复添加！")
            return
          }
          addShouhou(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        } catch (error) {
          console.error('检查订单号失败:', error);
          proxy.$modal.msgError("检查订单号失败，请稍后重试！")
        }
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除售后管理编号为"' + _ids + '"的数据项？').then(function() {
    return delShouhou(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/shouhou/export', {
    ...queryParams.value
  }, `shouhou_${new Date().getTime()}.xlsx`)
}

getList()
</script>
